# _*_ coding:utf-8 _*_
# @Time  : 2023.10.19
# @Author: zizlee
from fastapi import APIRouter, Body, Query
from pydantic import BaseModel
from db import FAConnection
from v1_all_api.all_response import AllResponse
from v1_all_api.all_utils import data_utils

user_datalib_api = APIRouter()


class UserDatalibGroupItem(BaseModel):
    name: str
    parent_id: int
    vcode: str
    user_id: int


@user_datalib_api.post('/group/')
def create_user_datalib_group(item: UserDatalibGroupItem = Body(...)):
    with FAConnection() as cursor:
        cursor.execute("INSERT INTO datalib_user_index_group (name,parent_id,vcode,user_id) VALUES (%s,%s,%s,%s);",
                       [item.name, item.parent_id, item.vcode, item.user_id])
    return AllResponse.operate_successfully()


@user_datalib_api.get('/group/')
def retrieve_user_datalib_group(user: int = Query(...), vcode: str = Query(...)):
    with FAConnection() as cursor:
        cursor.execute("SELECT * FROM datalib_user_index_group WHERE user_id=%s AND vcode=%s;",
                       [user, vcode])
        groups = list(cursor.fetchall())
    ret = data_utils.list2tree(data=groups, pkey='parent_id', ckey='id', fvalue=str(0))
    return AllResponse.operate_successfully(data=ret)


class UserGroupIndexItem(BaseModel):
    index_id: int
    name: str
    formula: str
    frequency: str
    unit: str
    is_diff: bool
    vcode: str
    user_id: int
    group_id: int
    source_plat: str
    source_id: str


@user_datalib_api.post('/groupIndex/')
def create_user_group_index(item: UserGroupIndexItem = Body(...)):
    sql = """
        INSERT INTO datalib_user_group_index (index_id,name,formula,frequency,unit,is_diff,vcode,user_id,group_id,source_plat,source_id)
        VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);
    """
    with FAConnection() as cursor:
        cursor.execute(sql, [item.index_id, item.name, item.formula.lower(), item.frequency, item.unit, item.is_diff,
                             item.vcode, item.user_id, item.group_id, item.source_plat, item.source_id])
    return AllResponse.operate_successfully()


@user_datalib_api.get('/groupIndex/')
def retrieve_user_group_index(gid: int = Query(...)):
    sql = """
        SELECT id,index_id,name,formula,frequency,unit,is_diff,vcode,user_id,group_id,source_plat,source_id
        FROM datalib_user_group_index WHERE group_id=%s;
    """
    with FAConnection() as cursor:
        cursor.execute(sql,
                       [gid])
        indexes = list(cursor.fetchall())
    return AllResponse.operate_successfully(data={'indexes': indexes})
